from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from .models import UsersModel
from .forms import LoginForm, RigsterForm


class LoginView(View):
    def get(self, request):
        loginForm = LoginForm()
        return render(request, 'login.html', {'loginform': loginForm})

    def post(self, request):
        loginForm = LoginForm(request.POST)
        if loginForm.is_valid():
            data = loginForm.cleaned_data
            user = authenticate(username=data['username'], password=data['password'])
            if user:
                login(request, user)
                return HttpResponse('login ok')

        return HttpResponse('login failed')


class RegisterView(View):
    def get(self, request):
        registerForm = RigsterForm()
        return render(request, 'register.html', {'registerform': registerForm})

    def post(self, request):
        registerForm = RigsterForm(request.POST)
        if registerForm.is_valid():
            registerForm.save()
            return HttpResponse('register ok')
        return HttpResponse('register failed')


def index_view():
    return HttpResponse('users')
